package com.icesoft.xsnow.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.icesoft.xsnow.common.core.constant.SecurityConstants;
import com.icesoft.xsnow.common.security.annotation.Inner;
import com.icesoft.xsnow.common.security.component.HackerUserProperties;
import com.icesoft.xsnow.common.security.dto.XSnowUser;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Optional;

/**
 * @program: xsnow
 * @description: 服务间接口鉴权处理逻辑
 * @author: xuefeng.gao
 * @create: 2019-05-27 11:25
 **/
@Slf4j
@Aspect
@Component
public class XsnowSecurityInnerAspect {
    @Autowired
    private  HttpServletRequest request;
    @Autowired
    private  HackerUserProperties hackerUserProperties;

    public XsnowSecurityInnerAspect(HttpServletRequest request){
        this.request = request;
    }
    /**
     * 权限校验
     **/
    @Around("@annotation(inner)")
    @SneakyThrows
    public Object around(ProceedingJoinPoint point, Inner inner) {
        String header = request.getHeader(SecurityConstants.FROM);
        if (inner.value() && !StrUtil.equals(SecurityConstants.FROM_IN, header)) {
            log.warn("访问接口 {} 没有权限", point.getSignature().getName());
            throw new AccessDeniedException("Access is denied");
        }
        return point.proceed();
    }


    /**
     * 黑客模式开启,模拟权限校验
     **/
    @Around(value = "execution(* com.icesoft.xsnow.common.security.component.PermissionService.hasPermission(..))")
    @SneakyThrows
    public Object hackerCheck(ProceedingJoinPoint point) {
        if(hackerUserProperties.isEnabled()){
            if(hackerUserProperties.getPermission().equals(HackerUserProperties.PermissionEnmu.admin.name())){
                return true;
            }else{
                return false;
            }
        }else{
            return point.proceed();
        }
    }


    /**
     * 黑客模式开启,获取用户
     **/
    @Around(value = "execution(* com.icesoft.xsnow.common.security.util.SecurityUtils.getUser())")
    @SneakyThrows
    public Object hackerUser(ProceedingJoinPoint point) {
        if(hackerUserProperties.isEnabled()){
            return null;
        }else{
            return point.proceed();
        }
    }



}
